package com.duolaibei.business.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.DIR;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.model.ShopListData;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.SysUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.utils.log.LogDebug;
import com.duolaibei.business.view.dialog.PhotoChooseDialog;
import com.duolaibei.business.view.dialog.ShopDialog;
import com.duolaibei.business.view.dialog.ShopStatusDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xlm on 2017/11/8 0008
 */

public class ShopEditActivity extends BaseActivity {

    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mViewTitle;

    private EditText mTextName;//门店名称
    private EditText mTextWorker;//员工ID
    private EditText mTextIntroduce;//门店描述
    private EditText mTextTel;//门店电话
    private EditText mTextAddress;//门店地址
    private EditText mTextLocation;//门店坐标
    private EditText mTextStatus;//门店状态

    @Inject(R.id.type_button_one)
    private TextView mViewCover;
    @Inject(R.id.type_button_two)
    private TextView mViewScene;
    @Inject(R.id.confirm_data)
    private TextView mViewConfirm;//提交资料
    @Inject(R.id.image_type1)
    private ImageView mImageViewCover;
    @Inject(R.id.image_type2)
    private ImageView mImageViewScene;

    private String name;//门店名称
    private String worker;//员工ID
    private String introduce;//门店描述
    private String tel;//门店电话
    private String address;//门店地址
    private String location;//门店坐标
    private String status;//门店状态
    private String mCurrentLon;//经度
    private String mCurrentLat;//纬度

    private static final int MAP_REQUST = 2;
    private String type;
    private String type_get;
    private static final int PERMISSON_CAMER = 1;
    private final static int PHOTO_1 = 0;
    private final static int PHOTO_2 = 1;
    private String photo_1;//门头照
    private String photo_2;//场景

    String path = DIR.TEMP_CAMERA;
    private final static int CAMERA_1 = 3;
    private final static int CAMERA_2 = 4;
    String photoPath;

    private String coverId;
    private String sceneId;

    private ShopListData.DataBeanX.DataBean dataBean;

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        try {
            dataBean = (ShopListData.DataBeanX.DataBean) intent.getSerializableExtra("shopbean");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_add_shop);
    }

    @Override
    protected void initViews() {
        mTextName = (EditText) findViewById(R.id.shop_name);
        mTextWorker = (EditText) findViewById(R.id.worker_name);
        mTextIntroduce = (EditText) findViewById(R.id.shop_introduce);
        mTextTel = (EditText) findViewById(R.id.shop_tel);
        mTextAddress = (EditText) findViewById(R.id.shop_address);
        mTextLocation = (EditText) findViewById(R.id.shop_location);
        mTextStatus = (EditText) findViewById(R.id.shop_status);
        if (dataBean == null) {
            mViewTitle.setText("新增门店");
            return;
        } else {
            mViewTitle.setText("修改门店");
        }
        if (!CommonUtil.isEmpty(dataBean.getName())) {
            mTextName.setText(dataBean.getName());
        }
        if (!CommonUtil.isEmpty(dataBean.getWorkmen_uid())) {
            mTextWorker.setText(dataBean.getWorkmen_uid());
        }
        if (!CommonUtil.isEmpty(String.valueOf(dataBean.getDescribe()))) {
            mTextIntroduce.setText(String.valueOf(dataBean.getDescribe()));
        }
        if (!CommonUtil.isEmpty(String.valueOf(dataBean.getTel()))) {
            mTextTel.setText(String.valueOf(dataBean.getTel()));
        }
        if (!CommonUtil.isEmpty(dataBean.getAddress())) {
            mTextAddress.setText(dataBean.getAddress());
        }
        if (!CommonUtil.isEmpty(dataBean.getLon())) {
            mTextLocation.setText("已定位");
            mTextLocation.setTextColor(Color.parseColor("#259B24"));
        }
        status = dataBean.getStatusX();
        if ("0".equals(status)) {
            mTextStatus.setText("关闭");
            mTextStatus.setTextColor(Color.parseColor("#259B24"));
        } else {
            mTextStatus.setText("打开");
            mTextStatus.setTextColor(Color.parseColor("#259B24"));
        }
        if (!CommonUtil.isEmpty(dataBean.getCover())) {
            Glide.with(this).load(dataBean.getCover()).into(mImageViewCover);
        }
        if (!CommonUtil.isEmpty(dataBean.getScene())) {
            Glide.with(this).load(dataBean.getScene().get(0).getUrl()).into(mImageViewScene);
        }
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {

    }

    @Override
    protected void onSetListener() {
        mLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTextWorker.setOnClickListener(this);
        mTextLocation.setOnClickListener(this);
        mViewCover.setOnClickListener(this);
        mViewScene.setOnClickListener(this);
        mViewConfirm.setOnClickListener(this);
        mImageViewCover.setOnClickListener(this);
        mImageViewScene.setOnClickListener(this);
        mTextStatus.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.worker_name:
                showShopDialog();
                break;
            case R.id.shop_location:
                startActivityForResult(new Intent(getThis(),
                        ShopLocationActivity.class), MAP_REQUST);
                break;
            case R.id.image_type1:
            case R.id.type_button_one:
                type = "cover";
                showPhotoChooseDialog();
                break;
            case R.id.image_type2:
            case R.id.type_button_two:
                type = "scene";
                showPhotoChooseDialog();
                break;
            case R.id.shop_status:
                showStatusDialog();
                break;
            case R.id.confirm_data:
                shopAddOrEdit();
                break;
        }
    }

    private ShopStatusDialog mShopStatusDialog;

    private void showStatusDialog() {
        if (mShopStatusDialog == null) {
            mShopStatusDialog = new ShopStatusDialog(getThis());
        }
        mShopStatusDialog.setCanceledOnTouchOutside(true);
        mShopStatusDialog.setListener(new ShopStatusDialog.Listener() {
            @Override
            public void open() {
                super.open();
                status = "1";
                mTextStatus.setText("打开");
                mTextStatus.setTextColor(Color.parseColor("#259B24"));
                mShopStatusDialog.dismiss();
            }

            @Override
            public void close() {
                super.close();
                status = "0";
                mTextStatus.setText("关闭");
                mTextStatus.setTextColor(Color.parseColor("#259B24"));
                mShopStatusDialog.dismiss();
            }
        });
        mShopStatusDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case MAP_REQUST:
                    mCurrentLon = data.getStringExtra("lon");
                    mCurrentLat = data.getStringExtra("lat");
                    mTextLocation.setText("已定位");
                    mTextLocation.setTextColor(Color.parseColor("#259B24"));
                    LogDebug.d("--------经度--------" + mCurrentLon);
                    LogDebug.d("--------纬度--------" + mCurrentLat);
                    break;
                //相册
                case PHOTO_1:
                    photo_1 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_1).into(mImageViewCover);
                    CommonUtil.getimage(photo_1);
                    upSceneOrCover(photo_1);
                    break;
                case PHOTO_2:
                    photo_2 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_2).into(mImageViewScene);
                    CommonUtil.getimage(photo_2);
                    upSceneOrCover(photo_2);
                    break;
                //相机
                case CAMERA_1:
                    photo_1 = photoPath;
                    Glide.with(this).load(photo_1).into(mImageViewCover);
                    CommonUtil.getimage(photo_1);
                    upSceneOrCover(photo_1);
                    break;
                case CAMERA_2:
                    photo_2 = photoPath;
                    Glide.with(this).load(photo_2).into(mImageViewScene);
                    CommonUtil.getimage(photo_2);
                    upSceneOrCover(photo_2);
                    break;
            }
        }
    }

    /**
     * 上传图片
     */
    private void upSceneOrCover(String photoPath) {
        String loginType = String.valueOf(PreferenceUtil.getParam(Preferences.LOGINTYPE, ""));
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.UPLOAD);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", loginType);
        if (!"merchant".equals(loginType)) {
            param.add("login_id", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINID, "")));
        }
        param.add("image", new File(photoPath));
        //签名算法
        Map<String, String> map = new HashMap<>();
        map.put("method", ApiName.UPLOAD);
        map.put("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        map.put("login_type", loginType);
        if (!"merchant".equals(loginType)) {
            map.put("login_id", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINID, "")));
        }
        param.add("sign", CommonUtil.toAscIIMd5String(map, true));
        showLoading("图片上传中");
        HttpUtils.getInstance().url(ApiName.API)
                .params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissLoading();
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissLoading();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil
                            .GsonToBean(string, ResponseResult.class);
                    showToast(result.getInfo());
                    if (result.getStatus() == 1) {
                        try {
                            JSONObject object = new JSONObject(string);
                            JSONObject object1 = object.getJSONObject("data");
                            if ("cover".equals(type)) {
                                coverId = object1.optString("id");
                            } else if ("scene".equals(type)) {
                                sceneId = object1.optString("id");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }

    private ShopDialog mShopDialog;

    /**
     * 选择员工信息
     */
    private void showShopDialog() {
        if (mShopDialog == null) {
            mShopDialog = new ShopDialog(getThis());
        }
        mShopDialog.setCancelable(true);
        mShopDialog.setShopDialogListener(new ShopDialog.ShopDialogListener() {
            @Override
            public void onItemSelected(String name, String id) {
                super.onItemSelected(name, id);
                mTextWorker.setText(name);
            }
        });
        mShopDialog.show();
    }

    /**
     * 选择照片
     */
    private PhotoChooseDialog mPhotoChooseDialog;

    private void showPhotoChooseDialog() {
        if (mPhotoChooseDialog == null) {
            mPhotoChooseDialog = new PhotoChooseDialog(this);
        }
        mPhotoChooseDialog.setListener(new PhotoChooseDialog.Listener() {
            @Override
            public void onSelectedCamera() {
                type_get = "take";
                if (checkCameraPermission(PERMISSON_CAMER)) {
                    if ("cover".equals(type)) {
                        takeCover();
                    } else if ("scene".equals(type)) {
                        takeScene();
                    }
                }
            }

            @Override
            public void onSelectedDCIM() {
                type_get = "choose";
                if (checkCameraPermission(PERMISSON_CAMER)) {
                    if ("cover".equals(type)) {
                        chooseCover();
                    } else if ("scene".equals(type)) {
                        chooseScene();
                    }
                }
            }
        });
        mPhotoChooseDialog.show();
    }

    /**
     * 选择门头照
     */
    private void chooseCover() {
        SysUtil.choosePhoto(this, PHOTO_1);
    }

    /**
     * 选择场景照
     */
    private void chooseScene() {
        SysUtil.choosePhoto(this, PHOTO_2);
    }

    /**
     * 拍摄门头照
     */
    private void takeCover() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_1);
    }

    /**
     * 拍摄场景照
     */
    private void takeScene() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_2);
    }

    @Override
    public void onCameraPermission(int result_code, boolean result) {
        if (result) {
            if (checkCameraPermission(PERMISSON_CAMER)) {
                if ("choose".equals(type_get)) {
                    if ("cover".equals(type)) {
                        chooseCover();
                    } else if ("scene".equals(type)) {
                        chooseScene();
                    }
                } else if ("take".equals(type_get)) {
                    if ("cover".equals(type)) {
                        takeCover();
                    } else if ("scene".equals(type)) {
                        takeScene();
                    }
                }
            }
        } else {
            showToast("拒绝相机功能，您将不能通过相机拍照");
        }
    }

    /**
     * 新增门店
     */
    private void shopAddOrEdit() {
        name = mTextName.getText().toString();
        worker = mTextWorker.getText().toString();
        introduce = mTextIntroduce.getText().toString();
        tel = mTextTel.getText().toString();
        address = mTextAddress.getText().toString();
        location = mTextLocation.getText().toString();
        status = mTextStatus.getText().toString();
        if ("关闭".equals(status)) {
            status = "0";
        } else if ("打开".equals(status)) {
            status = "1";
        }
        if (CommonUtil.isEmpty(name)) {
            showToast("请输入门店名称");
            return;
        }
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        if (dataBean == null) {
            param.add("method", ApiName.SHOPADD);
        } else {
            param.add("method", ApiName.SHOP_EDIT);
            param.add("shop_id", dataBean.getId());
        }
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", "merchant");//该接口只能商家登录访问
        param.add("name", name);
        if (!CommonUtil.isEmpty(worker)) {
            param.add("workmen_uid", worker);
        } else {
            if (dataBean != null) {
                param.add("workmen_uid", "");
            }
        }
        if (!CommonUtil.isEmpty(introduce)) {
            param.add("describe", introduce);
        } else {
            if (dataBean != null) {
                param.add("describe", "");
            }
        }
        if (!CommonUtil.isEmpty(tel)) {
            param.add("tel", tel);
        } else {
            if (dataBean != null) {
                param.add("tel", "");
            }
        }
        if (!CommonUtil.isEmpty(address)) {
            param.add("address", address);
        } else {
            if (dataBean != null) {
                param.add("address", "");
            }
        }
        if (!CommonUtil.isEmpty(location)) {
            param.add("lon", String.valueOf(mCurrentLon));//经度
            param.add("lat", String.valueOf(mCurrentLat));//纬度
        } else {
            if (dataBean != null) {
                param.add("lon", "");//经度
                param.add("lat", "");//纬度
            }
        }
        if (!CommonUtil.isEmpty(coverId)) {
            param.add("cover", coverId);
        } else {
            if (dataBean != null) {
                param.add("cover", "");
            }
        }
        if (!CommonUtil.isEmpty(sceneId)) {
            param.add("scene", sceneId);
        } else {
            if (dataBean != null) {
                param.add("scene", "");
            }
        }
        if (!CommonUtil.isEmpty(status)) {
            param.add("status", status);
        } else {
            showToast("请选择门店状态");
            return;
        }
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToast(result.getInfo());
                    if (result.getStatus() == 1) {
                        setResult(RESULT_OK);
                        finish();
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }


}
